package models

import (
	"blog_api/db"
	"blog_api/utils"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type PageVisitLog struct {
	Id         uint64 `gorm:"column(id)" json:"id"`
	Ip         string `gorm:"column(ip)" json:"ip"`
	Ip2int     uint64 `gorm:"column(ip2int)" json:"ip2int"`
	Location   string `gorm:"column(location)" json:"location"`
	Client     string `gorm:"column(client)" json:"client"`
	CreateTime int64  `gorm:"column(add_time)" json:"add_time"`
	VisitTimes int    `gorm:"column(visit_times)" json:"visit_times"`
	Page       string `gorm:"column(page)" json:"page"`
	Log        string `gorm:"column(log)" json:"log"`
	LatelyTime int64  `gorm:"column(lately_time)" json:"lately_time"`
}

func (*PageVisitLog) TableName() string {
	return "blog_page_visit_log"
}

var CODE2ERROR = []string{
	1000: "请求/pr页面：t参数为空",
	1001: "请求/pr页面：t参数错误",
	1002: "浏览文章",
}

/**
 * AddPageVisitLog
 * @Description: 点击文章——添加访问日志
 * @Author: Jazk-Z
 * @param log
 * @param art_id
 * @param view_type
 * @return int64
 */
func AddPageVisitLog(log PageVisitLog, art_id string, view_type int) bool {
	// 协程处理日志问题
	go RecodeViewLog(log, art_id, view_type)
	// 更新文章浏览次数
	db.Mysql.Model(&Article{}).Where("id", art_id).Update("view_numbers", gorm.Expr("view_numbers +1"))
	db.RedisZIncrBy(ARTILCE_TOP, 1, art_id)

	return true
}

type ArtDoc struct {
	Id    uint64 `gorm:"column(id)" json:"id"`
	Title string `gorm:"column(title)" json:"title"`
}

/**
 * RecodeViewLog
 * @Description: 记录访问日志和次数
 * @Author: Jazk-Z
 * @param log
 * @param view_type
 */
func RecodeViewLog(log PageVisitLog, art_id string, view_type int) {
	// es创建索引
	var art ArtDoc
	db.Mysql.Model(&Article{}).Where("id", art_id).Find(&art)
	art_doc, _ := json.Marshal(art)
	is_has := db.FindIndex(art_id, ES_ARTILCE_INDEX)
	fmt.Println("es—index是否存在",is_has)
	// if !is_has {
		res, err := db.CreateIndex(art_id, string(art_doc), ES_ARTILCE_INDEX)
		fmt.Println("es创建索引：", res, err)
	// }

	// 记录访问日志
	var ac int64
	db.Mysql.Model(&PageVisitLog{}).Where("ip2int", log.Ip2int).Count(&ac)
	if ac > 0 {
		db.Mysql.Model(&PageVisitLog{}).Where("ip2int = ? and page = ?", log.Ip2int, log.Page).Updates(map[string]interface{}{
			"lately_time": time.Now().Unix(),
			"visit_times": gorm.Expr("visit_times+?", 1),
		})
	} else {
		db.Mysql.Model(&PageVisitLog{}).Create(&log)
	}

	// 发送邮件提醒
	if view_type == 1 {
		// 邮件接收方，可以是多个接收人
		mailTo := []string{
			"zhaolongspace@163.com",
		}
		subject := "Blog_Waring_Log" // 邮件主题
		body, _ := json.Marshal(log) // 邮件正文

		err := utils.SendMail(mailTo, subject, string(body))
		if err != nil {
			fmt.Println("发送邮件失败")
		}
	}
}


func AdminPvl(limit, offset int, field, keyword string) ([]PageVisitLog, int64) {
	var a []PageVisitLog
	var c int64
	l := db.Mysql.Model(&PageVisitLog{})
	if keyword != "" {
		ids, err := db.SearchKeyword(keyword, ES_LABEL_INDEX)
		if err != nil {
			return a, 0
		}
		l.Where("id in (?)", ids)
	}
	l.Count(&c)
	l.Select(field).Order("create_time desc").Limit(limit).Offset(offset).Scan(&a)
	return a, c
}
